<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { PlatFormNavMenuConfig as menuItems} from "@/pages/PlatForm/const.js";

const router = useRouter()
const route = useRoute()

// 计算当前激活的菜单项
const activeIndex = computed(() => {
  // 获取当前路由名称
  const currentRouteName = route.name
  
  // 查找匹配的菜单项
  let matchedItem = null
  
  // 先检查顶级菜单
  matchedItem = menuItems.find(item => item.routeName === currentRouteName)
  if (matchedItem) return matchedItem.index
  
  // 再检查子菜单
  for (const item of menuItems) {
    if (item.children) {
      const matchedChild = item.children.find(child => child.routeName === currentRouteName)
      if (matchedChild) return matchedChild.index
    }
  }
  
  // 默认返回首页
  return '1'
})

const handleSelect = (index) => {
  const selectedItem = menuItems.find(item => item.index === index) ||
      [].concat(...menuItems.map(item => item.children || [])).find(child => child.index === index)
  if (selectedItem) {
    router.push({ name: selectedItem.routeName })
  }
}

</script>

<template>
  <el-menu :default-active="activeIndex" @select="handleSelect">
    <template v-for="item in menuItems" :key="item.index">
      <!-- 如果有子菜单 -->
      <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.index">
        <template #title>
          <i :class="item.icon"></i>
          <span>{{ item.title }}</span>
        </template>
        <el-menu-item v-for="child in item.children" :key="child.index" :index="child.index">
          {{ child.title }}
        </el-menu-item>
      </el-sub-menu>
      <!-- 如果没有子菜单 -->
      <el-menu-item v-else :index="item.index">
        <i :class="item.icon"></i>
        <span>{{ item.title }}</span>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<style scoped lang="less">
.el-menu {
  border: 0 !important;
}
</style>
